package com.atwei.mango.system.securityHandler;

import com.alibaba.fastjson.JSON;
import com.atwei.mango.system.apiModel.response.ApiResponse;
import com.atwei.mango.system.commen.globalConstant.GlobalConstantApi;
import com.atwei.mango.system.commen.utils.JWTUtil;
import com.atwei.mango.system.exception.ResponseEnum;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Classname UserLoginSuccessHandler
 * @Description 登陆成功控制类
 * @Date 2022/6/9 15:35
 * @Author liuwei
 */
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        SysAccount principal = (SysAccount)authentication.getPrincipal();
//        将token放入
        HashMap<String, String> tokenMap = new HashMap<String,String>(4){{
                put(GlobalConstantApi.TOKEN_NAME, JWTUtil.createAccessToken(principal));
                put(GlobalConstantApi.ACCOUNT_INFO, JSON.toJSONString(principal));
        }};
        ApiResponse.responseJson(httpServletResponse,ApiResponse.info(ResponseEnum.LOGIN_SUCCESS,tokenMap));
    }
}
